package com.freight.base.serviceimpl;

import com.freight.base.dao.DictDao;
import com.freight.base.entity.Dict;
import com.freight.base.entity.DictData;
import com.freight.base.service.DictDataService;
import com.freight.base.service.DictService;
import com.freight.base.vo.DictDataVo;
import com.freight.base.vo.PDictDataVo;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.websocket.Session;
import java.util.List;

/**
 * 字典接口实现
 *
 * @describe
 */
@Slf4j
@Service
@Transactional
public class DictServiceImpl implements DictService {

    @Autowired
    private DictDao dictDao;

    @Autowired
    private DictDataService dictDataService;


    @Override
    public DictDao getRepository() {
        return dictDao;
    }

    @Override
    public List<Dict> findAllOrderBySortOrder() {

        return dictDao.findAllOrderBySortOrder();
    }

    @Override
    public Dict findByType(String type) {

        return dictDao.findByType(type);
    }

    @Override
    public List<Dict> findByTitleOrTypeLike(String key) {

        return dictDao.findByTitleOrTypeLike(key);
    }

    @Override
    public List<PDictDataVo> getTwoDictByType(String type) {
        Dict dict = findByType(type);
        if (dict == null) {
            throw new FreightException("字典类型 " + type + " 不存在");
        }

        List<DictData> lists = dictDataService.findByDictId(dict.getId());
        List<PDictDataVo> parentRes = (List<PDictDataVo>) ObjectUtil.autoFillListEqFields(lists, PDictDataVo.class);

        for (PDictDataVo list : parentRes) {
            String subtype = list.getTitle();
            Dict subDict = findByType(subtype);
            List<DictData> subLists = dictDataService.findByDictId(subDict.getId());
            List<DictDataVo> subRes = (List<DictDataVo>) ObjectUtil.autoFillListEqFields(subLists, DictDataVo.class);
            list.setSubList(subRes);
        }
        return parentRes;
    }

    @Override
    public List<DictDataVo> getByType(String type) {
        Dict dict = findByType(type);
        if (dict == null) {
           return null;
        }
        List<DictData> list = dictDataService.findByDictId(dict.getId());
        List<DictDataVo> res = (List<DictDataVo>) ObjectUtil.autoFillListEqFields(list, DictDataVo.class);
        return res;
    }
}